#!/bin/bash
set -e

### 0. 基础变量
DISK="/dev/sda"
EFI_PART="${DISK}1"
ROOT_PART="${DISK}2"
MOUNTPOINT="/mnt"

### 1. 基础检查
echo "=== 检查磁盘和分区 ==="

# 检查目标磁盘是否存在
if [ ! -b "$DISK" ]; then
    echo "错误：磁盘 $DISK 不存在！"
    echo "请检查脚本中的 DISK 变量设置。"
    exit 1
fi

# 检查EFI分区是否存在
if [ ! -b "$EFI_PART" ]; then
    echo "错误：EFI分区 $EFI_PART 不存在！"
    echo "请先对磁盘进行分区。"
    exit 1
fi

# 检查根分区是否存在
if [ ! -b "$ROOT_PART" ]; then
    echo "错误：根分区 $ROOT_PART 不存在！"
    echo "请先对磁盘进行分区。"
    exit 1
fi

echo "✓ 磁盘检查通过：$DISK"
echo "✓ EFI分区：$EFI_PART"
echo "✓ 根分区：$ROOT_PART"

### 2. 检查并卸载已挂载的分区
echo "=== 检查挂载状态 ==="

# 检查并卸载EFI分区
if mountpoint -q "$EFI_PART" 2>/dev/null || findmnt -n "$EFI_PART" >/dev/null 2>&1; then
    echo "检测到EFI分区已挂载，正在卸载..."
    umount -l "$EFI_PART" 2>/dev/null || umount "$EFI_PART" 2>/dev/null || true
fi

# 检查并卸载根分区
if mountpoint -q "$ROOT_PART" 2>/dev/null || findmnt -n "$ROOT_PART" >/dev/null 2>&1; then
    echo "检测到根分区已挂载，正在卸载..."
    umount -l "$ROOT_PART" 2>/dev/null || umount "$ROOT_PART" 2>/dev/null || true
fi

# 检查并卸载挂载点
if mountpoint -q "$MOUNTPOINT" 2>/dev/null; then
    echo "检测到挂载点 $MOUNTPOINT 已挂载，正在卸载..."
    umount -l "$MOUNTPOINT" 2>/dev/null || umount -R "$MOUNTPOINT" 2>/dev/null || true
fi

echo "=== 格式化分区 ==="
mkfs.fat -F32 $EFI_PART
mkfs.btrfs -f $ROOT_PART

echo "=== 创建 Btrfs 子卷 ==="
mount $ROOT_PART $MOUNTPOINT
btrfs su cr $MOUNTPOINT/@
btrfs su cr $MOUNTPOINT/@home
btrfs su cr $MOUNTPOINT/@log
btrfs su cr $MOUNTPOINT/@cache
btrfs su cr $MOUNTPOINT/@snapshots
umount $MOUNTPOINT

echo "=== 挂载子卷 ==="
mount -o subvol=@,compress=zstd,ssd,noatime,space_cache=v2,discard=async $ROOT_PART $MOUNTPOINT
mkdir -p $MOUNTPOINT/{boot/efi,home,var/log,var/cache,.snapshots}

mount -o subvol=@home,compress=zstd,ssd,noatime,space_cache=v2,discard=async $ROOT_PART $MOUNTPOINT/home
mount -o subvol=@log,compress=zstd,ssd,noatime,space_cache=v2,discard=async $ROOT_PART $MOUNTPOINT/var/log
mount -o subvol=@cache,compress=zstd,ssd,noatime,space_cache=v2,discard=async $ROOT_PART $MOUNTPOINT/var/cache
mount -o subvol=@snapshots,compress=zstd,ssd,noatime,space_cache=v2,discard=async $ROOT_PART $MOUNTPOINT/.snapshots

mount $EFI_PART $MOUNTPOINT/boot/efi

### 3. 配置 Pacman 镜像源
echo "=== 配置 Pacman 镜像源 ==="

# 备份原始镜像源文件
cp /etc/pacman.d/mirrorlist /etc/pacman.d/mirrorlist.bak
echo "✓ 已备份原始镜像源文件"

# 将中科大镜像源添加到文件顶部
sed -i '1i\## 中国科学技术大学镜像源\nServer = https://mirrors.ustc.edu.cn/archlinux/$repo/os/$arch\n' /etc/pacman.d/mirrorlist
echo "✓ 已添加中科大镜像源"

# 可选：清理软件包缓存并更新数据库
pacman -Syy --noconfirm
echo "✓ 已更新软件包数据库"

echo "=== 安装基本系统 ==="
pacstrap $MOUNTPOINT base linux linux-firmware btrfs-progs snapper vim networkmanager sudo

echo "=== 生成 fstab ==="
genfstab -U $MOUNTPOINT >> $MOUNTPOINT/etc/fstab

arch-chroot $MOUNTPOINT /bin/bash <<EOF
set -e

echo "=== 配置 Snapper ==="
# 为根子卷创建 snapper 配置
snapper -c root create-config /

# 调整默认配置以适配子卷结构
sed -i 's/^TIMELINE_CREATE=.*/TIMELINE_CREATE="yes"/' /etc/snapper/configs/root
sed -i 's/^TIMELINE_CLEANUP=.*/TIMELINE_CLEANUP="yes"/' /etc/snapper/configs/root
sed -i 's/^TIMELINE_MIN_AGE=.*/TIMELINE_MIN_AGE="1800"/' /etc/snapper/configs/root
sed -i 's/^TIMELINE_LIMIT_HOURLY=.*/TIMELINE_LIMIT_HOURLY="10"/' /etc/snapper/configs/root
sed -i 's/^TIMELINE_LIMIT_DAILY=.*/TIMELINE_LIMIT_DAILY="7"/' /etc/snapper/configs/root
sed -i 's/^TIMELINE_LIMIT_WEEKLY=.*/TIMELINE_LIMIT_WEEKLY="4"/' /etc/snapper/configs/root
sed -i 's/^TIMELINE_LIMIT_MONTHLY=.*/TIMELINE_LIMIT_MONTHLY="3"/' /etc/snapper/configs/root

# 设置子卷路径
sed -i 's|^SUBVOLUME=.*|SUBVOLUME="/"|' /etc/snapper/configs/root

systemctl enable snapper-timeline.timer
systemctl enable snapper-cleanup.timer

echo "=== 配置 pacman hooks 自动快照 ==="
mkdir -p /etc/pacman.d/hooks

# 为 pacman 包操作创建自动快照钩子
cat > /etc/pacman.d/hooks/50-snapper-pre.hook <<HOOK
[Trigger]
Operation = Upgrade
Operation = Install
Operation = Remove
Type = Package
Target = *

[Action]
Description = 创建 pacman 操作前快照
When = PreTransaction
Exec = /usr/bin/snapper -c root create --description "pacman-pre" --cleanup-algorithm
HOOK

cat > /etc/pacman.d/hooks/50-snapper-post.hook <<HOOK
[Trigger]
Operation = Upgrade
Operation = Install
Operation = Remove
Type = Package
Target = *

[Action]
Description = 创建 pacman 操作后快照
When = PostTransaction
Exec = /usr/bin/snapper -c root create --description "pacman-post" --cleanup-algorithm
HOOK

EOF

echo "=== 基础系统安装完成！==="
echo ""
echo "接下来需要手动完成以下配置："
echo "1. 进入系统：arch-chroot /mnt"
echo "2. 配置 bootloader (systemd-boot 或 GRUB)"
echo "3. 设置时区、语言环境、主机名"
echo "4. 设置 root 密码和创建用户"
echo "5. 启用网络服务：systemctl enable NetworkManager"
echo "6. 重启系统"
echo ""
echo "脚本已自动配置："
echo "✓ Btrfs 子卷结构"
echo "✓ Snapper 快照系统"
echo "✓ Pacman 自动快照钩子"
echo "✓ 基础系统软件包"
echo "✓ 网络管理器"
echo "✓ 文本编辑器 vim"
